package com.p900.website.web.admin;

import com.p900.commons.domain.Advertisement;
import com.p900.commons.vo.BaseConditionVO;
import com.p900.website.service.AdvertisementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * Created by admin on 2015/5/15.
 */
@Controller("adminAdvertisement")
@RequestMapping("/admin")
public class AdvertisementController {

    @Autowired
    private AdvertisementService advertisementService;


    @RequestMapping("/advertisement/list")
    public String list(BaseConditionVO vo,
                       Model model){
        Page<Advertisement> advertisementPage = advertisementService.findAll(new PageRequest(vo.getPageNum() - 1, vo.getPageSize()));

        model.addAttribute("advertisements", advertisementPage);
        vo.setTotalCount(advertisementPage.getTotalElements());
        model.addAttribute("vo", vo);

        return "admin/advertisement/list";
    }

    @RequestMapping("/advertisement/add")
    public String add(){
        return "admin/advertisement/add";
    }

    @RequestMapping("/advertisement/edit/{id}")
    public String edit(@PathVariable Long id,
                       Model model){
        model.addAttribute("advertisement", advertisementService.findAdvertisement(id));
        return "admin/advertisement/edit";
    }

    @ResponseBody
    @RequestMapping("/advertisement/save")
    public Object save(Advertisement advertisement){
        Assert.notNull(advertisement, "advertisement is null");
        advertisementService.save(advertisement);
        return DwzResultVo.closeCurrentAndReloadListPage(Advertisement.class);
    }

    @ResponseBody
    @RequestMapping("/advertisement/delete/{id}")
    public Object delete(@PathVariable Long id){
        advertisementService.delete(id);
        return DwzResultVo.successResult();
    }
}
